# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/5/6 16:43
"""
from dataclasses import dataclass
from typing import List, Tuple

from DrissionPage import WebPage

from autoTask.taobao.sycm.gjc.competitorGoodKey.publicResource import MonitorCompetingProduct
from common.utils import urlUtil
from common.utils.web_page_util import MockTap, Input
from common.logger.log import log_


@dataclass
class SetCompetingProductsConfigAction:
    """
    设置竞争商品配置操作
    Attributes:
       p: 操作网页对象
       competing: 竞品元组 (1号,2号)
    """
    p: WebPage
    competing: Tuple[str, str]

    def __call__(self):
        log_.info("开始检查,设置竞品监控配置")
        self.goto_action_view()
        for competing in self.competing:
            # 获取已经配置的监控竞品
            p_list = self.get_competing_products_config()
            if not any(int(competing) == int(p.id) for p in p_list):
                # 添加竞品至配置
                MockTap(self.p(".anticon anticon-plus oui-canary-icon oui-canary-icon-plus"), "点击添加竞品",
                        after_delay=(1, 3))()
                Input(self.p(".ant-dropdown ant-dropdown-placement-bottomLeft")("tag:input@@class=ant-input"),
                      "输入竞品编号搜索失败", vals=competing, after_delay=(4, 6))()
                MockTap(self.p(".sycm-common-select-name"), "点击搜索结果首选项失败", after_delay=(1, 3))()
                add_e = self.p("c:.oui-canary-btn", timeout=0)
                # 判断是否需要取消竞品
                if not add_e.states.is_enabled:
                    ok_list = [x for x in p_list if x.cancel_ele]
                    if len(ok_list) == 0:
                        log_.warning("您店铺已经不能取消监控商品已得添加新的监控商品!")
                        break
                    MockTap(ok_list[0].cancel_ele, "点击取消监控商品失败", after_delay=(3, 5))()
                    MockTap(self.p("x://button[@class='ant-btn ant-btn-primary']"), "取消商品监控操作失败",
                            after_delay=(1, 3), reduce_scope=(10, 5))()
                    add_e.wait.enabled(timeout=10)
                MockTap(self.p("c:.oui-canary-btn"), "添加监控商品失败", after_delay=(1, 3),
                        is_ele_unavailable_err=True, reduce_scope=(5, 15))()
                MockTap(self.p("x://button[@class='ant-btn ant-btn-primary ant-btn-sm']"),
                        "确认添加商品监控操作失败",
                        after_delay=(3, 5))()
                self.p.refresh()
                self.p.wait.load_complete(30)
            else:
                log_.info(f"该竞品已经加入监控: {competing}")
        log_.info("竞品监控配置完毕")

    def goto_action_view(self):
        """
        前往竞争商品配置页面
        :return:
        """
        if not self.p.url.startswith("https://sycm.taobao.com/mc/ci/config/rival?activeKey=item"):
            MockTap(self.p("x://span[.='竞争']"), "跳转到 [竞争] 标签页失败", before_delay=(1, 3))()
            self.p.wait.load_complete(30)
            MockTap(self.p.eles("竞争配置")[1], before_delay=(1, 3), reduce_scope=(10, 10))()
            self.p.wait.load_complete(30)
            MockTap(self.p("@@class^oui-tab-switch-item@@text():竞争商品"), "跳转到 [竞争商品] 标签页失败",
                    before_delay=(1, 3))()
            self.p.wait.load_complete(30)

    def get_competing_products_config(self) -> List[MonitorCompetingProduct]:
        """
        获取竞争配置的监控商品列表
        :return: 监控商品列表
        """
        self.goto_action_view()
        es = self.p.eles(".list-item-box item")
        result = []
        for e in es:
            # 获取左侧的文本框
            left_text_div = e.ele(".sycm-common-shop-td-title-wrapper subTitleWrapper")
            # 获取商品标题的a标签
            a = left_text_div("t:a", timeout=0)
            # 获取当前商品取消监控按钮
            cancel_e = e.ele(".sycm-mc-link-td-wrapper vertical")("t:a@@text():取消", timeout=0)
            date = left_text_div(".subTitle", timeout=0).text
            result.append(
                MonitorCompetingProduct(a.text, a.link, date, int(urlUtil.url_get_params(a.link, "id")), cancel_e))
        return result
